package com.leoman.utils;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * Created by Administrator on 2016/8/26 0026.
 */
public class FFmpegUtils {
    /**
     * 音频格式转换
     * 将上传的录音转为mp3格式
     *
     * @param webRoot    项目的根目录R
     * @param sourcePath 文件的相对地址
     */
    public static void changeMP3(String webRoot, String sourcePath) {
        //File file = new File(sourcePath);
        String targetPath = sourcePath + ".mp3";//转换后文件的存储地址，直接将原来的文件名后加mp3后缀名
        Runtime run = null;
        try {
            run = Runtime.getRuntime();
            long start = System.currentTimeMillis();
            Process p = run.exec(webRoot + "ffmpeg -i " + webRoot + sourcePath + " -acodec libmp3lame " + webRoot + targetPath);
            //执行ffmpeg.exe,前面是ffmpeg.exe的地址，中间是需要转换的文件地址，后面是转换后的文件地址。-i是转换方式，意思是可编码解码，mp3编码方式采用的是libmp3lame
            //释放进程
            p.getOutputStream().close();
            p.getInputStream().close();
            p.getErrorStream().close();
            p.waitFor();
            long end = System.currentTimeMillis();
            System.out.println(sourcePath + " convert success, costs:" + (end - start) + "ms");
            //删除原来的文件
            //if(file.exists()){
            //  file.delete();
            //}
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //run调用lame解码器最后释放内存
            run.freeMemory();
        }
    }

    /**
     * linux下利用ffmpeg转换音频文件为mp3格式
     *
     * @param infile  目标文件路径
     * @param outfile 转换之后的文件路径
     * @return
     */
    public static boolean ffmpegTransfer(String infile, String outfile) {
        // ffmpeg -i 1.mp3 -ac 1 -ar 8000 1.amr  //MP3转换AMR
        // ffmpeg -i 1.amr 1.mp3                 //AMR转换MP3
        String orders = "ffmpeg -i " + infile + " -acodec libamr_nb -ab 12.2k -ar 8000 -ac 1 " + outfile;
        try {
            Runtime rt = Runtime.getRuntime();
            Process proc = rt.exec(new String[]{"sh", "-c", orders});

            InputStream stderr = proc.getErrorStream();
            InputStreamReader isr = new InputStreamReader(stderr);
            BufferedReader br = new BufferedReader(isr);
            String line = null;

            while ((line = br.readLine()) != null)
                System.out.println(line);
            int exitVal = proc.waitFor();
            System.out.println("Process exitValue: " + exitVal);

            // 转换完成后删除文件
            rt.exec("rm -f " + infile);
        } catch (Throwable t) {
            t.printStackTrace();
            return false;
        }
        return true;
    }
}
